<script setup lang="ts">
import { ref } from "vue";
import request from "@/utils/request";
import { UploadRequestOptions } from "element-plus";
import { s } from "vite/dist/node/types.d-aGj9QkWt";
import { useUserStore } from "@/store/modules/user";
const userStore = useUserStore();

// 搜索相关
const getDefaultSearchForm = () => ({
  pageNo: 1,
  pageSize: 10,
  name: "",
  status: "",
  phone: "",
});

const searchForm = ref(getDefaultSearchForm());
const list = ref([]);
const total = ref(0);

const rules = ref({
  name: [{ required: true, message: "公司名称不能为空", trigger: "blur" }],
  legalName: [{ required: true, message: "法人姓名不能为空", trigger: "blur" }],
  idCardNo: [{ required: true, message: "法人身份证号不能为空", trigger: "blur" }],
  mobile: [{ required: true, message: "手机号不能为空", trigger: "blur" },
    {
      pattern:/^1[3-9]\d{9}$/,
      message: "请输入有效的手机号码",
      trigger: "blur",
    }],
  email: [{ required: true, message: "邮箱不能为空", trigger: "blur" }],
  address: [{ required: true, message: "地址不能为空", trigger: "blur" }],
});

// 服务选择相关
const serviceDialogVisible = ref(false);
const services = ref([]);
const selectedServiceId = ref<number | null>(null);
const serviceCount = ref(1);

const fetchServices = () => {
  request.get("/api/v1/product/list").then((res) => {
    services.value = res.data;
  });
};

const submitServiceSelection = () => {
  if (!selectedServiceId.value || serviceCount.value <= 0) {
    ElMessage.error("请选择服务并输入有效的数量");
    return;
  }

  const companyId = editId.value; // 获取公司ID
  if (!companyId) {
    ElMessage.error("公司ID不存在，请刷新页面后重试");
    return;
  }
  console.log("提交数据:", {
    companyId: editId.value,
    productId: selectedServiceId.value,
    num: serviceCount.value,
  });
  request.post("/api/v1/company/auth", {
    companyId: editId.value,
    productId: selectedServiceId.value,
    num: serviceCount.value,
  }).then(() => {
    ElMessage.success("授权成功");
    serviceDialogVisible.value = false;
  }).catch((err) => {
    console.error(err);
    ElMessage.error("授权失败，请稍后重试");
  });
};


// 通用方法
const getList = () => {
  request.post("/api/v1/company/search", searchForm.value).then((res) => {
    list.value = res.data.list;
    total.value = res.data.total;
  });
};

const resetSearch = () => {
  searchForm.value = getDefaultSearchForm();
  getList();
};

getList();

// 表单相关
const addForm = ref({
  name: "",
  licenseImg: "",
  legalName: "",
  idCardNo: "",
  idCardFront: "",
  idCardBack: "",
  mobile: "",
  email: "",
  address: "",
});

const resetAddForm = () => {
  addForm.value = {
    name: "",
    licenseImg: "",
    legalName: "",
    idCardNo: "",
    idCardFront: "",
    idCardBack: "",
    mobile: "",
    email: "",
    address: "",
  };
};

const dialogVisible = ref(false);

const validateForm = ref();

const uploadedFilesCount = ref(0); // 用来记录上传成功的文件数量

const uploadFile = (field: keyof typeof addForm.value, options: UploadRequestOptions) => {
  const fd = new FormData();
  fd.append("file", options.file);

  // 上传文件
  request
      .post("/api/v1/files", fd, {
        headers: {
          "Content-Type": "multipart/form-data",
        },
      })
      .then((res) => {
        // 更新文件URL
        addForm.value[field] = res.data.url;

        // 增加上传成功的文件数量
        uploadedFilesCount.value++;

        // 当所有必需的文件都上传完时，开始提取信息
        if (
            uploadedFilesCount.value === 3 &&
            addForm.value.idCardFront &&
            addForm.value.idCardBack &&
            addForm.value.licenseImg
        ) {
          const companyForm = {
            idCardFront: addForm.value.idCardFront,
            idCardBack: addForm.value.idCardBack,
            licenseImg: addForm.value.licenseImg,
          };

          // 调用后端接口提取信息
          request
              .post("/api/v1/company/extract", companyForm)
              .then((response) => {
                const filledData = response.data;
                // 回填表单字段
                if (filledData.legalName) {
                  addForm.value.legalName = filledData.legalName; // 法人姓名
                }
                if (filledData.idCardNo) {
                  addForm.value.idCardNo = filledData.idCardNo; // 法人身份证号
                }
                if (filledData.companyName) {
                  addForm.value.name = filledData.companyName; // 公司名称
                }
              })
              .catch((err) => {
                console.error("信息提取失败", err);
                ElMessage.error("信息提取失败，请稍后重试");
              });
        }
      })
      .catch((err) => {
        console.error("上传失败", err);
        ElMessage.error("文件上传失败，请稍后重试");
      });
};



const isEdit = ref(false);
const editId = ref(null);

const handleEdit = (id: number) => {
  isEdit.value = true;
  editId.value = id;

  request
      .get(`/api/v1/company/detail/${id}`)
      .then((res) => {
        const company = res.data;
        if (company) {
          addForm.value = { ...company };
          dialogVisible.value = true;
        } else {
          ElMessage.error("未找到公司数据，请刷新后重试");
        }
      })
      .catch((err) => {
        console.error(err);
        ElMessage.error("获取公司详情失败，请稍后重试");
      });
};

const handleSubmit = () => {
  validateForm.value.validate((valid: boolean) => {
    if (valid) {
      const endpoint = isEdit.value ? "/api/v1/company/update" : "/api/v1/company/add";

      const payload = isEdit.value
          ? { ...addForm.value, id: editId.value }
          : addForm.value;
      request
          .post(endpoint, payload)
          .then(() => {
            getList();
            dialogVisible.value = false;
            resetAddForm();
            ElMessage.success(isEdit.value ? "编辑成功" : "新增成功");
          })
          .catch((error) => {
            console.error(error);
            ElMessage.error(isEdit.value ? "编辑失败" : "新增失败，请稍后重试");
          });
    }
  });
};

const handleDialogClose = () => {
  dialogVisible.value = false;
  resetAddForm();
  isEdit.value = false;
  editId.value = null;
};

const handleDelete = (id: number) => {
  ElMessageBox.confirm("此操作将永久删除该公司信息，是否继续？", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
      .then(() => {
        request
            .delete(`/api/v1/company/delete/${id}`)
            .then(() => {
              ElMessage.success("删除成功");
              getList();
            })
            .catch((err) => {
              console.error(err);
              ElMessage.error("删除失败，请稍后重试");
            });
      })
      .catch(() => {
        ElMessage.info("已取消删除");
      });
};

const handleView = (id: number) => {
  serviceDialogVisible.value = true;
  fetchServices();
  editId.value = id;

};

const auditDialogVisible = ref(false); // 审核弹窗显示状态
const auditStatus = ref(null); // 审核状态：1表示通过，2表示驳回
const currentAuditId = ref(null); // 当前审核的公司ID
const isLoading = ref(false); // 加载状态
const auditReason = ref(""); // 驳回原因
const auditCompanyDetails = ref({}); // 存储公司详细信息
const currentUserId = ref<number | null>(null); // 假设这里存储当前用户的ID

// 获取当前用户ID（可能是从 Vuex 或其他状态管理工具获取）
const getCurrentUserId = () => {
  // 假设你已经有一个方法来获取当前用户ID
  return userStore.user.userId ; // 这里用静态值2L作为示例
};

// 在组件加载时获取当前用户的ID
onMounted(() => {
  currentUserId.value = getCurrentUserId();
});

// 重置弹窗内容
const resetDialog = () => {
  auditStatus.value = null; // 重置审核状态
  auditReason.value = ""; // 清空驳回原因
  auditCompanyDetails.value = {}; // 清空公司详情
};

// 处理审核按钮点击事件
const handleAudit = (id: number) => {
  auditDialogVisible.value = true;
  currentAuditId.value = id;

  // 获取公司详情
  request
      .get(`/api/v1/company/detail/${id}`)
      .then((res) => {
        auditCompanyDetails.value = res.data; // 存储公司信息
      })
      .catch((err) => {
        console.error("获取公司详情失败:", err);
        ElMessage.error("获取公司详情失败，请稍后重试");
      });
};

// 关闭弹窗并重置内容
const closeDialog = () => {
  resetDialog(); // 重置弹窗内容
  auditDialogVisible.value = false; // 关闭弹窗
};

// 提交审核
const submitAudit = async () => {
  if (auditStatus.value === null) {
    ElMessage.error("请选择审核结果");
    return;
  }
  if (auditStatus.value === 2 && !auditReason.value.trim()) {
    ElMessage.error("请输入驳回原因");
    return;
  }

  isLoading.value = true; // 显示加载状态
  try {
    await request.post("/api/v1/company/audit", {
      id: currentAuditId.value,
      status: auditStatus.value,
      count: auditStatus.value === 2 ? auditReason.value : undefined, // 驳回原因
      createBy: currentUserId.value, // 当前用户ID
    });
    ElMessage.success("审核操作成功");
    closeDialog(); // 成功后关闭弹窗并重置内容
    getList(); // 刷新公司列表
  } catch (err) {
    console.error("审核操作失败:", err);
    ElMessage.error("审核操作失败，请稍后重试");
  } finally {
    isLoading.value = false; // 恢复加载状态
  }
};

// 监听取消操作
const handleCancel = () => {
  closeDialog(); // 关闭弹窗并重置内容
};

</script>

<template>
  <div>
    <!-- 原搜索与表格部分保持不变 -->
    <el-card :body-style="{ paddingBottom: '0' }">
      <el-form inline>
        <el-form-item label="公司名称">
          <el-input v-model="searchForm.name" placeholder="请输入公司名称"></el-input>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="searchForm.phone" placeholder="请输入公司手机号"></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 200px">
            <el-option label="待审核" :value="0"></el-option>
            <el-option label="通过" :value="1"></el-option>
            <el-option label="驳回" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="getList" type="primary">查询</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card style="margin-top: 16px">
      <template #header>
        <el-button type="primary" @click="dialogVisible = true">新增</el-button>
      </template>
      <el-table :data="list">
        <el-table-column prop="name" label="公司名称" width="250"></el-table-column>
        <el-table-column prop="legalName" label="公司法人"></el-table-column>
        <el-table-column label="法人身份证正面" width="150">
          <template #default="{ row }">
            <el-image
                :src="row.idCardFront"
                style="width: 50px"
                fit="cover"
                :preview-src-list="[row.idCardFront]"
                :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="法人身份证反面" width="150">
          <template #default="{ row }">
            <el-image
                :src="row.idCardBack"
                style="width: 50px; cursor: pointer;"
                fit="cover"
                :preview-src-list="[row.idCardBack]"
                :preview-teleported="true"
            />
          </template>
        </el-table-column>


        <el-table-column label="营业执照" width="150">
          <template #default="{ row }">
            <el-image
                :src="row.licenseImg"
                style="width: 50px"
                fit="cover"
                :preview-src-list="[row.licenseImg]"
                :preview-teleported="true"
            />
          </template>
        </el-table-column>
        <el-table-column label="状态">
          <template #default="{ row }">
            <el-tag v-if="row.status === 0" type="warning">待审核</el-tag>
            <el-tag v-if="row.status === 1" type="success">通过</el-tag>
            <el-tag v-if="row.status === 2" type="danger">驳回</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="count" label="驳回原因" width="200"></el-table-column>
        <el-table-column prop="mobile" label="手机号" width="200"></el-table-column>
        <el-table-column prop="email" label="邮箱" width="250"></el-table-column>
        <el-table-column prop="address" label="地址" width="250" show-overflow-tooltip></el-table-column>
        <el-table-column label="操作" width="400" fixed="right" align="center">
          <template #default="{ row }">
            <el-button type="primary" @click="handleEdit(row.id)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(row.id)">删除</el-button>
            <el-button type="success" @click="handleView(row.id)">申请</el-button>
            <el-button type="warning" @click="handleAudit(row.id)" v-if="row.status != 1">审核</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div style="margin: 16px">
        <el-pagination @current-change="currentChange" :total="total" layout="prev, pager, next" />
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" title="新增公司" :before-close="handleDialogClose">
      <el-form ref="validateForm" :model="addForm" :rules="rules" label-position="top">
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address"></el-input>
        </el-form-item>
        <div style="display: flex; align-items: center; justify-content: space-between;">
          <el-form-item label="法人身份证正面(人像)">
            <el-upload
                class="avatar-uploader"
                accept="image/*"
                :http-request="(options) => uploadFile('idCardFront', options)"
                :show-file-list="false"
            >
              <img v-if="addForm.idCardFront" :src="addForm.idCardFront" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="法人身份证反面(国徽)">
            <el-upload
                class="avatar-uploader"
                accept="image/*"
                :http-request="(options) => uploadFile('idCardBack', options)"
                :show-file-list="false"
            >
              <img v-if="addForm.idCardBack" :src="addForm.idCardBack" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="营业执照">
            <el-upload
                class="avatar-uploader"
                accept="image/*"
                :http-request="(options) => uploadFile('licenseImg', options)"
                :show-file-list="false"
            >
              <img v-if="addForm.licenseImg" :src="addForm.licenseImg" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon">
                <Plus />
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>
        <el-form-item label="公司名称" prop="name">
          <el-input v-model="addForm.name"></el-input>
        </el-form-item>
        <el-form-item label="法人姓名" prop="legalName">
          <el-input v-model="addForm.legalName"></el-input>
        </el-form-item>
        <el-form-item label="法人身份证号" prop="idCardNo">
          <el-input v-model="addForm.idCardNo"></el-input>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleDialogClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
    <!-- 服务选择弹窗 -->
    <el-dialog v-model="serviceDialogVisible" title="选择服务">
      <el-table :data="services" border>
        <el-table-column label="选择" width="80">
          <template #default="{ row }">
            <el-radio :label="row.id" v-model="selectedServiceId" />
          </template>
        </el-table-column>
        <el-table-column prop="name" label="服务名称" />
        <el-table-column prop="description" label="服务描述" />
        <el-table-column prop="price" label="单个客服价格" />
        <el-table-column prop="unit" label="服务天数" />
      </el-table>
      <el-input-number v-model="serviceCount" :min="1" style="margin: 16px 0" placeholder="购买数量" />
      <template #footer>
        <el-button @click="serviceDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitServiceSelection(editId)">确定</el-button>
      </template>
    </el-dialog>

    <el-dialog
        v-model="auditDialogVisible"
        title="企业审核"
        width="700px"
        custom-class="custom-audit-dialog">
      <div class="audit-container">
        <!-- 公司信息卡片 -->
        <div class="info-card">
          <h3>公司信息</h3>
          <div class="info-row">
            <span class="info-label">公司名称：</span>
            <span class="info-value">{{ auditCompanyDetails.name }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">法人姓名：</span>
            <span class="info-value">{{ auditCompanyDetails.legalName }}</span>
          </div>
          <div class="info-row">
            <span class="info-label">身份证号：</span>
            <span class="info-value">{{ auditCompanyDetails.idCardNo }}</span>
          </div>
          <div class="info-images">
            <div class="image-item">
              <p>营业执照</p>
              <el-image
                  :src="auditCompanyDetails.licenseImg"
                  class="image-preview"
                  fit="cover"
                  :preview-src-list="[auditCompanyDetails.licenseImg]"
                  :preview-teleported="true"
              />
            </div>
            <div class="image-item">
              <p>身份证正面</p>
              <el-image
                  :src="auditCompanyDetails.idCardFront"
                  class="image-preview"
                  fit="cover"
                  :preview-src-list="[auditCompanyDetails.idCardFront]"
                  :preview-teleported="true"
              />
            </div>
            <div class="image-item">
              <p>身份证反面</p>
              <el-image
                  :src="auditCompanyDetails.idCardBack"
                  class="image-preview"
                  fit="cover"
                  :preview-src-list="[auditCompanyDetails.idCardBack]"
                  :preview-teleported="true"
              />
            </div>
          </div>
        </div>

        <!-- 审核操作卡片 -->
        <div class="action-card">
          <h3>审核操作</h3>
          <el-radio-group v-model="auditStatus" class="status-radio-group">
            <el-radio :label="1" class="status-radio">通过</el-radio>
            <el-radio :label="2" class="status-radio">驳回</el-radio>
          </el-radio-group>
          <el-input
              v-if="auditStatus === 2"
              type="textarea"
              placeholder="请输入驳回原因"
              v-model="auditReason"
              class="reject-reason-input"
          ></el-input>
        </div>
      </div>

      <!-- 弹窗底部 -->
      <template #footer>
        <el-button @click="auditDialogVisible = false" class="cancel-button">取消</el-button>
        <el-button type="primary" @click="submitAudit" class="submit-button">确定</el-button>
      </template>
    </el-dialog>




  </div>
</template>
<style scoped>

/* Container for the company information */
.audit-container {
  display: flex;
  flex-direction: column;
  padding: 20px;
}

/* Style for the info card */
.info-card {
  margin-bottom: 20px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
}

/* Rows inside the info card */
.info-row {
  display: flex;
  align-items: center;
  margin-bottom: 10px;
}

/* Left-aligned labels */
.info-label {
  font-weight: bold;
  width: 120px;
  text-align: left;
}

/* Right-aligned values */
.info-value {
  flex: 1;
  text-align: left;
}

/* Container for the images */
.info-images {
  display: flex;
  justify-content: center;
  gap: 20px;
  margin-top: 20px;
}

/* Each image item (for the license and ID cards) */
.image-item {
  text-align: center;
  width: 120px;  /* Adjust width to make the images smaller */
}

.image-item p {
  margin-bottom: 10px;
  font-weight: bold;
}

/* Reduced image size */
.image-preview {
  width: 100px;  /* Smaller width */
  height: 100px; /* Smaller height */
  object-fit: cover;  /* Ensures the image covers the area without distorting */
  border-radius: 5px;
  border: 1px solid #e4e7ed;
}

/* Action card styling */
.action-card {
  margin-top: 20px;
  padding: 15px;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
}

/* Style for the radio buttons */
.status-radio-group {
  margin-bottom: 15px;
}

/* Textarea for rejection reason */
.reject-reason-input {
  width: 100%;
  height: 80px;
  margin-top: 10px;
}

/* Footer buttons styling */
.el-button {
  margin-right: 10px;
}

.cancel-button {
  background-color: #f5f7fa;
  border-color: #dcdfe6;
}

.submit-button {
  background-color: #409eff;
  color: white;
}


.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}

.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
